package com.ctshk.rpc.cms.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ctshk.common.constant.ElasticSearchConstant;
import com.ctshk.common.dto.Result;
import com.ctshk.common.elasticsearch.config.ElasticSearchConfiguration;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageReq;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.cms.constant.CmsConstant;
import com.ctshk.rpc.cms.constant.Constant;
import com.ctshk.rpc.cms.dto.*;
import com.ctshk.rpc.cms.enums.SingleItemType;
import com.ctshk.rpc.cms.req.*;
import com.ctshk.rpc.cms.service.*;
import com.ctshk.rpc.hotel.dto.h5.HotelHotDTO;
import com.ctshk.rpc.hotel.dto.h5.HotelHotsH5DTO;
import com.ctshk.rpc.hotel.dto.h5.HotelSearchDTO;
import com.ctshk.rpc.hotel.req.h5.HotelQueryReq;
import com.ctshk.rpc.hotel.service.IHotelH5Service;
import com.ctshk.rpc.localfun.dto.es.HotLocalFunDto;
import com.ctshk.rpc.localfun.req.PCLocalFunQueryReq;
import com.ctshk.rpc.localfun.service.ILocalFunH5ProductService;
import com.ctshk.rpc.scenic.dto.app.inner.ScenicTicketListDTO;
import com.ctshk.rpc.scenic.req.TicketRecommendReq;
import com.ctshk.rpc.scenic.service.app.IScenicTicketRecommendService;
import com.ctshk.rpc.season.dto.AppFixedSeasonProductDTO;
import com.ctshk.rpc.season.req.AppSearchFixedProductReq;
import com.ctshk.rpc.season.service.ISeasonFixedProductService;
import com.ctshk.rpc.system.dto.AreaDTO;
import com.ctshk.rpc.system.dto.MainDataRowFieldDataDTO;
import com.ctshk.rpc.system.req.AreaQueryReq;
import com.ctshk.rpc.system.req.MainDataRowFieldDataReq;
import com.ctshk.rpc.system.service.IMainDataTableService;
import com.ctshk.rpc.system.service.ISysAreaService;
import com.ctshk.rpc.system.service.ISysUserService;
import com.ctshk.rpc.tour.dto.TourHomeHotTypeAndMsgDTO;
import com.ctshk.rpc.tour.dto.TourPcHomeCatalogAndCmsDTO;
import com.ctshk.rpc.tour.dto.TripHomeCatalogDTO;
import com.ctshk.rpc.tour.dto.TripTypeDTO;
import com.ctshk.rpc.tour.dto.cache.TripGroup;
import com.ctshk.rpc.tour.req.LocalHotSearchReq;
import com.ctshk.rpc.tour.service.ISeriesTripAppService;
import com.ctshk.rpc.user.dto.UserMessageListDTO;
import com.ctshk.rpc.user.req.UserMessagePageReq;
import com.ctshk.rpc.user.service.IUserMessageService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.time.LocalDate;
import java.time.temporal.TemporalUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * app版本 服务实现类
 * </p>
 *
 * @author lys
 * @since 2021/06/10
 */
@DubboService
public class AppHomeServiceImpl implements IAppHomeService {

    @DubboReference
    private ISysUserService sysUserService;

    @DubboReference
    private INoticePositionService noticePositionService;

    @DubboReference
    private IBannerPositionService bannerPositionService;

    @DubboReference
    private ISysAreaService areaService;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @DubboReference
    private ISeriesTripAppService seriesTripAppService;

    @DubboReference
    private IScenicTicketRecommendService iScenicTicketEsSearchService;

    @DubboReference
    private ISeasonFixedProductService seasonFixedProductService;

    @DubboReference
    private IHotelH5Service hotelH5Service;

    @DubboReference
    private ILocalFunH5ProductService iLocalFunAppProductService;

    @Autowired
    private IBaiDuApiService baiDuApiService;

    @DubboReference
    private IUserMessageService userMessageService;

    @Autowired
    private IContentClassificationService contentClassificationService;

    @DubboReference
    private IMainDataTableService mainDataTableService;

    @DubboReference
    private IScenicTicketRecommendService iScenicTicketRecommendService;

    /**
     * @param req
     * @return
     */
    @Override
    public Result<List<AppHomeSearchResDTO>> search(AppHomeSearchReq req, TokenUser tokenUser) {
        // 如果精确匹配到目的地，拼接单项
        if (ObjectUtils.isEmpty(req)) {
            return Result.failed(SystemError.SYS_402);
        }

        AreaDTO areaDTO = searchMatch(req.getKey());
        List<AppHomeSearchResDTO> result = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(areaDTO)) {
            String str = getSearchResult(areaDTO);
            Long id = areaDTO.getId();
            List<SingleItemType> itemList = SingleItemType.getItemList();
            for (SingleItemType singleItemType : itemList) {
                if (singleItemType.getCode() != -1) {
                    AppHomeSearchResDTO appHomeSearchResDTO = new AppHomeSearchResDTO();
                    appHomeSearchResDTO.setResult(str);
                    appHomeSearchResDTO.setType(singleItemType.getCode());
                    appHomeSearchResDTO.setIcon(singleItemType.getImg());
                    appHomeSearchResDTO.setIsFull(0);
                    appHomeSearchResDTO.setId(id);
                    if (singleItemType.getCode() != 0) {
                        appHomeSearchResDTO.setParent(singleItemType.getMsg());
                    }
                    result.add(appHomeSearchResDTO);
                }
            }
            Collections.sort(result);
            return Result.success(result);
        }

        // 如果没有精确匹配到目的地，组装模糊匹配结果
        // 模糊匹配目的地 - 3个目的地
        List<AreaDTO> areaDTOS = areaService.queryListEs(new AreaQueryReq().setName(req.getKey()).setSize(3));
        if (CollectionUtil.isNotEmpty(areaDTOS)) {
            for (AreaDTO area : areaDTOS) {
                AppHomeSearchResDTO appHomeSearchResDTO = new AppHomeSearchResDTO();
                if (ObjectUtils.isNotEmpty(area.getCityTraditional())) {
                    appHomeSearchResDTO.setResult(area.getCityTraditional());
                    appHomeSearchResDTO.setParent(area.getProvinceTraditional());
                    appHomeSearchResDTO.setId(area.getId());
                    appHomeSearchResDTO.setType(SingleItemType.LOCALFUN.getCode());
                    appHomeSearchResDTO.setIsFull(1);
                    appHomeSearchResDTO.setIcon(SingleItemType.SEARCH.getImg());
                    result.add(appHomeSearchResDTO);
                    continue;
                }
                if (ObjectUtils.isNotEmpty(area.getProvinceTraditional())) {
                    appHomeSearchResDTO.setResult(area.getProvinceTraditional());
                    appHomeSearchResDTO.setParent(area.getCountryTraditional());
                    appHomeSearchResDTO.setId(area.getId());
                    appHomeSearchResDTO.setType(SingleItemType.LOCALFUN.getCode());
                    appHomeSearchResDTO.setIcon(SingleItemType.SEARCH.getImg());
                    result.add(appHomeSearchResDTO);
                    continue;
                }
                if (ObjectUtils.isNotEmpty(area.getCountryTraditional())) {
                    appHomeSearchResDTO.setResult(area.getCountryTraditional());
                    appHomeSearchResDTO.setId(area.getId());
                    appHomeSearchResDTO.setType(SingleItemType.LOCALFUN.getCode());
                    appHomeSearchResDTO.setIcon(SingleItemType.SEARCH.getImg());
                    result.add(appHomeSearchResDTO);
                }
            }
        }

        // 3个酒店
        HotelQueryReq hotelQueryReq = new HotelQueryReq();
        hotelQueryReq.setCityName(req.getKey());
        hotelQueryReq.setRoomNum(1);
        hotelQueryReq.setCheckInDate(LocalDate.now());
        hotelQueryReq.setCheckOutDate(LocalDate.now().plusDays(1));
        hotelQueryReq.setChildrenNum(1);
        hotelQueryReq.setAdultNum(1);
        PageResponse<HotelSearchDTO> search = hotelH5Service.search(hotelQueryReq);
        if (ObjectUtils.isNotEmpty(search)) {
            List<HotelSearchDTO> records = search.getRecords();
            for (HotelSearchDTO homeHotRecommendDTO : records) {
                AppHomeSearchResDTO appHomeSearchResDTO = new AppHomeSearchResDTO();
                appHomeSearchResDTO.setResult(homeHotRecommendDTO.getName());
                appHomeSearchResDTO.setId(homeHotRecommendDTO.getId());
                appHomeSearchResDTO.setIsFull(1);
                appHomeSearchResDTO.setType(SingleItemType.HOTEL.getCode());
                appHomeSearchResDTO.setIcon(SingleItemType.SEARCH.getImg());
                result.add(appHomeSearchResDTO);
            }
        }

        /* 套票目前查询的数据库，暂时不做
        // 2个自由行套票
        AppHomeHotRecommendSearchReq appHomeHotRecommendSearchReq = new AppHomeHotRecommendSearchReq();
        appHomeHotRecommendSearchReq.setPage(1);
        appHomeHotRecommendSearchReq.setSize(2);
        appHomeHotRecommendSearchReq.setChannelId(req.getChannelId());
        List<HomeHotRecommendDTO> seasonHotRecommenc = findSeasonHotRecommenc(appHomeHotRecommendSearchReq, tokenUser);
        for (HomeHotRecommendDTO homeHotRecommendDTO : seasonHotRecommenc) {
            AppHomeSearchResDTO appHomeSearchResDTO = new AppHomeSearchResDTO();
            appHomeSearchResDTO.setResult(homeHotRecommendDTO.getTitle());
            appHomeSearchResDTO.setId(homeHotRecommendDTO.getId());
            appHomeSearchResDTO.setIsFull(1);
            appHomeSearchResDTO.setType(SingleItemType.SEASON.getCode());
            appHomeSearchResDTO.setIcon(SingleItemType.SEARCH.getImg());
            result.add(appHomeSearchResDTO);
        }*/

        // 1个門票
        TicketRecommendReq ticketRecommendReq = new TicketRecommendReq();
        ticketRecommendReq.setName(req.getKey());
        ticketRecommendReq.setChannelId(req.getChannelId());
        Result<PageResponse<ScenicTicketListDTO>> pageResponseResult = iScenicTicketRecommendService.selectTicketRecommendList(ticketRecommendReq, 1, 1);
        if(ObjectUtils.isNotEmpty(pageResponseResult)){
            List<ScenicTicketListDTO> records = pageResponseResult.getData().getRecords();
            for (ScenicTicketListDTO homeHotRecommendDTO : records) {
                AppHomeSearchResDTO appHomeSearchResDTO = new AppHomeSearchResDTO();
                appHomeSearchResDTO.setResult(homeHotRecommendDTO.getTitle());
                appHomeSearchResDTO.setId(homeHotRecommendDTO.getProductId());
                appHomeSearchResDTO.setIsFull(1);
                appHomeSearchResDTO.setType(SingleItemType.SCENIC.getCode());
                appHomeSearchResDTO.setIcon(SingleItemType.SEARCH.getImg());
                result.add(appHomeSearchResDTO);
            }
        }

        return Result.success(result);
    }

    /**
     * 精确匹配检索用户输入的值
     *
     * @return
     */
    private AreaDTO searchMatch(String key) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        int[] i1 = {2, 3, 4};
        boolQuery.should(QueryBuilders.boolQuery()
                .should(QueryBuilders.matchPhraseQuery("countrySimple.keyword", key))
                .should(QueryBuilders.matchPhraseQuery("countryTraditional.keyword", key))
                .should(QueryBuilders.matchPhraseQuery("countryPinyin.keyword", key))
                .mustNot(QueryBuilders.termsQuery("level", i1))
        );

        int[] i2 = {1, 3, 4};
        boolQuery.should(QueryBuilders.boolQuery()
                .should(QueryBuilders.matchPhraseQuery("provinceSimple.keyword", key))
                .should(QueryBuilders.matchPhraseQuery("provinceTraditional.keyword", key))
                .should(QueryBuilders.matchPhraseQuery("provincePinyin.keyword", key))
                .mustNot(QueryBuilders.termsQuery("level", i2))
        );

        int[] i3 = {1, 2, 4};
        boolQuery.should(QueryBuilders.boolQuery()
                .should(QueryBuilders.matchPhraseQuery("citySimple.keyword", key))
                .should(QueryBuilders.matchPhraseQuery("cityTraditional.keyword", key))
                .should(QueryBuilders.matchPhraseQuery("cityPinyin.keyword", key))
                .mustNot(QueryBuilders.termsQuery("level", i3))
        );
        sourceBuilder.query(boolQuery);
        SearchRequest searchRequest = new SearchRequest(ElasticSearchConstant.SYSTEM_AREA).source(sourceBuilder);

        try {
            SearchResponse search = restHighLevelClient.search(searchRequest, ElasticSearchConfiguration.COMMON_OPTIONS);
            SearchHit[] hits = search.getHits().getHits();
            if (ObjectUtils.isEmpty(hits)) {
                return null;
            }
            String source = hits[0].getSourceAsString();
            return JSON.parseObject(source, AreaDTO.class);
        } catch (IOException e) {
            throw new BusinessException(SystemError.ES_IO_EXCEPTION_19004);
        }
    }

    private String getSearchResult(AreaDTO areaDTO) {
        if (ObjectUtils.isNotEmpty(areaDTO.getCityTraditional())) {
            return areaDTO.getCityTraditional();
        }
        if (ObjectUtils.isNotEmpty(areaDTO.getProvinceTraditional())) {
            return areaDTO.getProvinceTraditional();
        }
        if (ObjectUtils.isNotEmpty(areaDTO.getCountryTraditional())) {
            return areaDTO.getCountryTraditional();
        }
        return null;
    }

    /**
     * APP首页CMS聚合
     *
     * @param req
     * @return
     */
    @Override
    public Result<AppHomeCmsDTO> getHomeCMS(AppHomeCMSReq req, TokenUser tokenUser) {
        AppHomeCmsDTO appHomeCmsDTO = new AppHomeCmsDTO();
        // 轮播banner图
        Result<BannerPositionListDTO> app_banner = bannerPositionService.getBannerPositionByCode(CmsConstant.APP_BANNER);
        if (app_banner.isSuccess()) {
            List<BannerDTO> banners = app_banner.getData().getBanners();
            List<H5BannerResDTO> bannerResDTOS = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(banners)) {
                for (BannerDTO bannerDTO : banners) {
                    H5BannerResDTO bannerResDTO = new H5BannerResDTO();
                    bannerResDTO.setPng(bannerDTO.getBannerUrl());
                    if (ObjectUtils.isNotEmpty(bannerDTO.getLinkTypeDto())) {
                        bannerResDTO.setLinkUrl(bannerDTO.getLinkTypeDto().getLinkUrl());
                        bannerResDTO.setType(bannerDTO.getLinkTypeDto().getLinkType());
                        bannerResDTO.setFunctionPage(bannerDTO.getLinkTypeDto().getFunctionPage());
                        bannerResDTO.setProductId(bannerDTO.getLinkTypeDto().getProductId());
                        bannerResDTO.setProductName(bannerDTO.getLinkTypeDto().getProductName());
                    }
                    bannerResDTOS.add(bannerResDTO);
                }
                appHomeCmsDTO.setRotate(bannerResDTOS);
            }
        }


        // 公告
        Result<NoticePositionListDTO> app_notice = noticePositionService.getNoticePositionByCode(CmsConstant.APP_NOTICE);
        if (app_notice.isSuccess()) {
            List<NoticeDTO> noticeDTOS = app_notice.getData().getNoticeDTOS();
            List<TipDTO> tipDTOS = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(noticeDTOS)) {
                for (NoticeDTO noticeDTO : noticeDTOS) {
                    TipDTO tipDTO = new TipDTO();
                    tipDTO.setTitle(noticeDTO.getTitle());
                    tipDTO.setContent(noticeDTO.getNoticeContent());
                    tipDTOS.add(tipDTO);
                }
                appHomeCmsDTO.setTips(tipDTOS);
            }
        }

        // 消息数量
        if (ObjectUtils.isNotEmpty(tokenUser)) {
            UserMessagePageReq userMessagePageReq = new UserMessagePageReq();
            userMessagePageReq.setUserId(tokenUser.getId());
            Result<PageResponse<UserMessageListDTO>> pageResponseResult = userMessageService.queryPage(userMessagePageReq);
            int size = (int) pageResponseResult.getData().getTotal();
            appHomeCmsDTO.setNumber(size);
        }

        // 最近分社距离
        if (ObjectUtils.isNotEmpty(req.getLon()) && ObjectUtils.isNotEmpty(req.getLat())) {
            BOQueryReq boQueryReq = new BOQueryReq();
            boQueryReq.setLon(req.getLon());
            boQueryReq.setLat(req.getLat());
            Result<List<BranchOfficeDTO>> query = baiDuApiService.query(boQueryReq);
            List<BranchOfficeDTO> data = query.getData();
            Integer meter = data.get(0).getMeter();
            appHomeCmsDTO.setDistance(meter);
        }

        // 金刚位
        Result<BannerPositionListDTO> app_operate = bannerPositionService.getBannerPositionByCode(CmsConstant.APP_OPERATE);
        if (app_operate.isSuccess()) {
            List<BannerDTO> operate = app_operate.getData().getBanners();
            List<OperateDTO> operateDTOS = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(operate)) {
                for (BannerDTO bannerDTO : operate) {
                    OperateDTO operateDTO = new OperateDTO();
                    operateDTO.setIcon(bannerDTO.getBannerUrl());
                    operateDTO.setName(bannerDTO.getTitle());
                    if (ObjectUtils.isNotEmpty(bannerDTO.getLinkTypeDto())) {
                        operateDTO.setType(bannerDTO.getLinkTypeDto().getLinkType());
                        operateDTO.setFunctionPage(bannerDTO.getLinkTypeDto().getFunctionPage());
                    }
                    operateDTOS.add(operateDTO);
                }
                appHomeCmsDTO.setOperate(operateDTOS);
            }
        }

        // 金刚位1
        Result<BannerPositionListDTO> app_operate1 = bannerPositionService.getBannerPositionByCode(CmsConstant.APP_OPERATE_1);
        if (app_operate1.isSuccess()) {
            List<BannerDTO> operate1 = app_operate1.getData().getBanners();
            List<OperateDTO> operate1DTOS = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(operate1)) {
                for (BannerDTO bannerDTO : operate1) {
                    OperateDTO operateDTO = new OperateDTO();
                    operateDTO.setIcon(bannerDTO.getBannerUrl());
                    operateDTO.setName(bannerDTO.getTitle());
                    if (ObjectUtils.isNotEmpty(bannerDTO.getLinkTypeDto())) {
                        operateDTO.setType(bannerDTO.getLinkTypeDto().getLinkType());
                        operateDTO.setFunctionPage(bannerDTO.getLinkTypeDto().getFunctionPage());
                    }
                    operate1DTOS.add(operateDTO);
                }
                appHomeCmsDTO.setOperate1(operate1DTOS);
            }
        }

        // 金刚位下方banner
        Result<BannerPositionListDTO> app_banner1 = bannerPositionService.getBannerPositionByCode(CmsConstant.APP_BANNER_1);
        if (app_banner1.isSuccess()) {
            List<BannerDTO> bannerDTOS1 = app_banner1.getData().getBanners();
            List<H5BannerResDTO> bannerResDTOS1 = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(bannerDTOS1)) {
                for (BannerDTO bannerDTO : bannerDTOS1) {
                    H5BannerResDTO bannerResDTO = new H5BannerResDTO();
                    bannerResDTO.setPng(bannerDTO.getBannerUrl());
                    if (ObjectUtils.isNotEmpty(bannerDTO.getLinkTypeDto())) {
                        bannerResDTO.setLinkUrl(bannerDTO.getLinkTypeDto().getLinkUrl());
                        bannerResDTO.setType(bannerDTO.getLinkTypeDto().getLinkType());
                        bannerResDTO.setProductId(bannerDTO.getLinkTypeDto().getProductId());
                        bannerResDTO.setProductName(bannerDTO.getLinkTypeDto().getProductName());
                        bannerResDTO.setFunctionPage(bannerDTO.getLinkTypeDto().getFunctionPage());
                    }
                    bannerResDTOS1.add(bannerResDTO);
                }
                appHomeCmsDTO.setBanner(bannerResDTOS1);
            }
        }
        return Result.success(appHomeCmsDTO);
    }

    /**
     * PC首页CMS聚合
     *
     * @param req
     * @param currentUser
     * @return
     */
    @Override
    public Result<PcHomeCmsDTO> getPCHomeCMS(AppHomeCMSReq req, TokenUser currentUser) {
        PcHomeCmsDTO pcHomeCmsDTO = new PcHomeCmsDTO();
        // 旅行团分类目录
        Result<TourPcHomeCatalogAndCmsDTO> tripHomeCatalogAndBannerAndNotic = seriesTripAppService.getTripHomeCatalogAndBannerAndNotic();
        List<TripHomeCatalogDTO> catalogs = tripHomeCatalogAndBannerAndNotic.getData().getCatalogs();
        List<HomeTourCatalogDTO> homeTourCatalogDTOS = EntityUtil.copyList(catalogs, HomeTourCatalogDTO.class);
        pcHomeCmsDTO.setCatalogs(homeTourCatalogDTOS);

        // 轮播banner图
        Result<BannerPositionListDTO> pc_banner = bannerPositionService.getBannerPositionByCode(CmsConstant.PC_BANNER);
        if (pc_banner.isSuccess()) {
            List<BannerDTO> bannerDTOS = pc_banner.getData().getBanners();
            List<BannerResDTO> bannerResDTOS = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(bannerDTOS)) {
                for (BannerDTO bannerDTO : bannerDTOS) {
                    BannerResDTO bannerResDTO = new BannerResDTO();
                    bannerResDTO.setRotate(bannerDTO.getBannerUrl());
                    if (ObjectUtils.isNotEmpty(bannerDTO.getLinkTypeDto())) {
                        bannerResDTO.setLinkUrl(bannerDTO.getLinkTypeDto().getLinkUrl());
                        bannerResDTO.setType(bannerDTO.getLinkTypeDto().getLinkType());
                        bannerResDTO.setFunctionPage(bannerDTO.getLinkTypeDto().getFunctionPage());
                        bannerResDTO.setProductId(bannerDTO.getLinkTypeDto().getProductId());
                        bannerResDTO.setProductName(bannerDTO.getLinkTypeDto().getProductName());
                    }
                    bannerResDTOS.add(bannerResDTO);
                }
                pcHomeCmsDTO.setRotate(bannerResDTOS);
            }
        }

        // 公告
        Result<NoticePositionListDTO> pc_notice = noticePositionService.getNoticePositionByCode(CmsConstant.PC_NOTICE);
        if (pc_notice.isSuccess()) {
            List<NoticeDTO> noticeDTOS = pc_notice.getData().getNoticeDTOS();
            List<TipDTO> tipDTOS = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(noticeDTOS)) {
                for (NoticeDTO noticeDTO : noticeDTOS) {
                    TipDTO tipDTO = new TipDTO();
                    tipDTO.setTitle(noticeDTO.getTitle());
                    tipDTO.setContent(noticeDTO.getNoticeContent());
                    tipDTOS.add(tipDTO);
                }
                pcHomeCmsDTO.setTips(tipDTOS);
            }
        }

        // 文档
        Result<ContentClassificationListDTO> cts_news = contentClassificationService.getContentClassificationByCode(CmsConstant.CTS_NEWS);
        List<ContentDTO> contentDTOS = cts_news.getData().getContentDTOS();
        if (ObjectUtils.isNotEmpty(contentDTOS)) {
            List<HomeContentDTO> homeContentDTOS = new ArrayList<>();
            for (ContentDTO contentDTO : contentDTOS) {
                HomeContentDTO homeContentDTO = new HomeContentDTO();
                homeContentDTO.setId(contentDTO.getId());
                homeContentDTO.setTitle(contentDTO.getArticleTitle());
                homeContentDTO.setSubTitle(contentDTO.getArticleIntroduce());
                homeContentDTO.setCoverPhotoUrl(contentDTO.getPictureUrl());
                homeContentDTO.setDate(contentDTO.getGmtCreate().toLocalDate());
                homeContentDTOS.add(homeContentDTO);
            }
            pcHomeCmsDTO.setContents(homeContentDTOS);
        }

        return Result.success(pcHomeCmsDTO);
    }


    /**
     * APP首页热门推荐聚合
     *
     * @param req
     * @return
     */
    @Override
    public Result<List<HomeHotRecommendDTO>> hotRecommend(AppHomeHotRecommendSearchReq req, TokenUser tokenUser) {
        // 1:旅行团 2:自由行套票 3:酒店 4:门票 5:当地玩乐
        switch (req.getType()) {
            case 1:
                return Result.success(findTourHotRecommenc(req));
            case 2:
                return Result.success(findSeasonHotRecommenc(req, tokenUser));
            case 3:
                return Result.success(findHotelHotRecommenc(req));
            case 4:
                return Result.success(findScenicHotRecommenc(req));
            case 5:
                return Result.success(findLocalFunHotRecommenc(req));
            default:
                return Result.failed(SystemError.SYS_400);
        }
    }

    /**
     * PC首页产品推荐聚合
     *
     * @param channelId
     * @param tokenUser
     * @return
     */
    @Override
    public Result<PCHomeProductGroupDTO> pcGroupInfo(Long channelId, TokenUser tokenUser) {
        PCHomeProductGroupDTO pcHomeProductGroupDTO = new PCHomeProductGroupDTO();
        // 旅行团
        TourHomeHotTypeAndMsgDTO tourHomeHotTypeAndMsgDTO = seriesTripAppService.tripHotTypeAndMsgInfo();
        List<TripTypeDTO> typeDTOS = tourHomeHotTypeAndMsgDTO.getTypeDTOS();
        List<HomeGroupTypeDTO> homeGroupTypeDTOS = new ArrayList();
        for (TripTypeDTO typeDTO : typeDTOS) {
            HomeGroupTypeDTO homeGroupTypeDTO = new HomeGroupTypeDTO();
            homeGroupTypeDTO.setId(typeDTO.getId());
            homeGroupTypeDTO.setName(typeDTO.getTitle());
            homeGroupTypeDTOS.add(homeGroupTypeDTO);
        }
        Collections.sort(homeGroupTypeDTOS);
        pcHomeProductGroupDTO.setTourTypes(homeGroupTypeDTOS);
        List<HomeHotRecommendDTO> tourHotRecommenc = findTourHotRecommenc(new AppHomeHotRecommendSearchReq().setSize(8).setChannelId(channelId));
        pcHomeProductGroupDTO.setTour(tourHotRecommenc);

        // 自由行
        MainDataRowFieldDataReq mainDataRowFieldDataReq = new MainDataRowFieldDataReq();
        mainDataRowFieldDataReq.setTid(1376823777639460865L);
        mainDataRowFieldDataReq.setFid(1376823817288216577L);
        List<MainDataRowFieldDataDTO> mainDataRowFieldDataDTOS = mainDataTableService.queryDataFieldLikeName(mainDataRowFieldDataReq);
        List<HomeGroupTypeDTO> seasonTypes = new ArrayList<>();
        for (MainDataRowFieldDataDTO mainDataRowFieldDataDTO : mainDataRowFieldDataDTOS) {
            HomeGroupTypeDTO homeGroupTypeDTO = new HomeGroupTypeDTO();
            homeGroupTypeDTO.setId(mainDataRowFieldDataDTO.getId().toString());
            homeGroupTypeDTO.setName(mainDataRowFieldDataDTO.getFieldValue());
            seasonTypes.add(homeGroupTypeDTO);
        }
        pcHomeProductGroupDTO.setSeasonTypes(seasonTypes);
        List<HomeHotRecommendDTO> seasonHotRecommenc = findSeasonHotRecommenc(new AppHomeHotRecommendSearchReq().setSize(8).setChannelId(channelId), tokenUser);
        pcHomeProductGroupDTO.setSeason(seasonHotRecommenc);

        // 酒店
        pcHomeProductGroupDTO.setHotel(findHotelHotRecommenc(new AppHomeHotRecommendSearchReq().setSize(8)));

        return Result.success(pcHomeProductGroupDTO);
    }

    @Override
    public Result<List<HomeHotRecommendDTO>> groupSearch(AppHomeHotRecommendSearchReq req, TokenUser user) {
        boolean isHot = ObjectUtils.isEmpty(req.getGroupId());
        List<HomeHotRecommendDTO> groupInfo = new ArrayList<>();
        // 旅行团请求参数封装
        if (req.getType().intValue() == SingleItemType.TOUR.getCode().intValue()) {
            LocalHotSearchReq localHotSearchReq = new LocalHotSearchReq();
            localHotSearchReq.setChannelId(req.getChannelId());
            localHotSearchReq.setPage(req.getPage());
            localHotSearchReq.setSize(ObjectUtils.isEmpty(req.getSize()) || req.getSize() <= 0 ? 8 : req.getSize());
            localHotSearchReq.setGourpCode(isHot ? null : req.getGroupId());

            // 旅行团请求结果封装
            List<TripGroup> hotGroupInfo = seriesTripAppService.getHotGroupInfo(localHotSearchReq);
            for (TripGroup tripGroup : hotGroupInfo) {
                HomeHotRecommendDTO homeHotRecommendDTO = EntityUtil.copy(tripGroup, HomeHotRecommendDTO.class);
                homeHotRecommendDTO.setId(tripGroup.getTripId());
                groupInfo.add(homeHotRecommendDTO);
            }
        }

        // 自由行(套票)请求参数封装
        if (req.getType().intValue() == SingleItemType.SEASON.getCode().intValue()) {
            Long userId = null;
            if (ObjectUtils.isNotEmpty(user)) {
                userId = user.getId();
            }
            AppSearchFixedProductReq appSearchFixedProductReq = new AppSearchFixedProductReq();
            appSearchFixedProductReq.setChannelId(req.getChannelId());
            appSearchFixedProductReq.setIsRecommend(isHot ? 1 : 0);
            Long seasonTypeId = null;
            try {
                if (!isHot) {
                    seasonTypeId = Long.valueOf(req.getGroupId());
                }
            } catch (Exception e) {
                return Result.failed(SystemError.CMS_23005);
            }
            appSearchFixedProductReq.setSeasonTypeId(seasonTypeId);

            // 自由行请求结果封装
            Result<PageResponse<AppFixedSeasonProductDTO>> pageResponseResult = seasonFixedProductService.onLineSeasonSearch(userId, appSearchFixedProductReq);
            List<AppFixedSeasonProductDTO> records = pageResponseResult.getData().getRecords();
            for (AppFixedSeasonProductDTO record : records) {
                HomeHotRecommendDTO homeHotRecommendDTO = new HomeHotRecommendDTO();
                homeHotRecommendDTO.setId(record.getProductId());
                homeHotRecommendDTO.setBasePrice(record.getProductPrice());
                homeHotRecommendDTO.setCoverPhotoUrl(record.getIntroducePicture());
                homeHotRecommendDTO.setIsHot(record.getIsRecommend().equals("1") ? 0 : 1);
                homeHotRecommendDTO.setTitle(record.getSubtitle());
                groupInfo.add(homeHotRecommendDTO);
            }
        }

        return Result.success(groupInfo);
    }

    /**
     * 旅行团热门推荐检索
     *
     * @param req
     * @return
     */
    private List<HomeHotRecommendDTO> findTourHotRecommenc(AppHomeHotRecommendSearchReq req) {
        List<TripGroup> hotGroupInfo = seriesTripAppService
                .getHotGroupInfo(new LocalHotSearchReq()
                        .setChannelId(req.getChannelId())
                        .setSize(ObjectUtils.isEmpty(req.getSize()) ? ElasticSearchConstant.PAGE_SIZE : req.getSize()));
        List<HomeHotRecommendDTO> hotRecommendDTOS = new ArrayList<>();
        for (TripGroup tripGroup : hotGroupInfo) {
            HomeHotRecommendDTO copy = EntityUtil.copy(tripGroup, HomeHotRecommendDTO.class);
            copy.setId(tripGroup.getTripId());
            hotRecommendDTOS.add(copy);
        }
        return hotRecommendDTOS;
    }

    /**
     * 固定套票热门推荐检索
     *
     * @param req
     * @return
     */
    private List<HomeHotRecommendDTO> findSeasonHotRecommenc(AppHomeHotRecommendSearchReq req, TokenUser tokenUser) {
        Long id = null;
        if (ObjectUtils.isNotEmpty(tokenUser)) {
            id = tokenUser.getId();
        }
        AppSearchFixedProductReq appSearchFixedProductReq = new AppSearchFixedProductReq();
        appSearchFixedProductReq.setChannelId(req.getChannelId());
        Integer page = ObjectUtils.isEmpty(req.getPage()) ? 1 : req.getPage();
        appSearchFixedProductReq.setPageNo(page);
        Integer size = ObjectUtils.isEmpty(req.getSize()) ? ElasticSearchConstant.PAGE_SIZE : req.getSize();
        appSearchFixedProductReq.setPageSize(size);
        Result<PageResponse<AppFixedSeasonProductDTO>> pageResponseResult = seasonFixedProductService.onLineSeasonSearch(id, appSearchFixedProductReq);
        PageResponse<AppFixedSeasonProductDTO> data = pageResponseResult.getData();
        List<AppFixedSeasonProductDTO> records = data.getRecords();
        List<HomeHotRecommendDTO> hotRecommendDTOS = new ArrayList<>();
        for (AppFixedSeasonProductDTO record : records) {
            HomeHotRecommendDTO homeHotRecommendDTO = new HomeHotRecommendDTO();
            homeHotRecommendDTO.setId(record.getProductId());
            homeHotRecommendDTO.setBasePrice(record.getProductPrice());
            homeHotRecommendDTO.setCoverPhotoUrl(record.getIntroducePicture());
            //  homeHotRecommendDTO.setIsHot(record.getIsRecommend().equals("1") ? 0 : 1);
            homeHotRecommendDTO.setTitle(record.getSubtitle());
            hotRecommendDTOS.add(homeHotRecommendDTO);
        }
        return hotRecommendDTOS;
    }

    /**
     * 酒店热门推荐检索
     *
     * @param req
     * @return
     */
    private List<HomeHotRecommendDTO> findHotelHotRecommenc(AppHomeHotRecommendSearchReq req) {
        PageReq pageReq = new PageReq();
        pageReq.setPageSize(req.getSize());
        PageResponse<HotelHotsH5DTO> hotelHotsH5DTOPageResponse = hotelH5Service.queryRecommendations2(pageReq);
        List<HotelHotsH5DTO> records = hotelHotsH5DTOPageResponse.getRecords();
        List<HotelHotDTO> hotelHotDTOS = new ArrayList<>();
        String string = JSON.toJSONString(records);
        List<HotelHotsH5DTO> hotelHotsH5DTOS = JSONArray.parseArray(string, HotelHotsH5DTO.class);
        for (HotelHotsH5DTO record : hotelHotsH5DTOS) {
            hotelHotDTOS.addAll(record.getHotels());
        }
        List<HomeHotRecommendDTO> hotRecommendDTOS = new ArrayList<>();
        for (HotelHotDTO hotel : hotelHotDTOS) {
            HomeHotRecommendDTO homeHotRecommendDTO = new HomeHotRecommendDTO();
            homeHotRecommendDTO.setId(hotel.getId());
            homeHotRecommendDTO.setBasePrice(hotel.getPrice());
            // appHomeHotRecommendDTO.setIsHot(); 暂无字段，待补
            homeHotRecommendDTO.setTitle(hotel.getName());
            homeHotRecommendDTO.setCoverPhotoUrl(hotel.getCoverMap());
            hotRecommendDTOS.add(homeHotRecommendDTO);
        }
        return hotRecommendDTOS;
    }

    /**
     * 门票热门推荐检索
     *
     * @param req
     * @return
     */
    private List<HomeHotRecommendDTO> findScenicHotRecommenc(AppHomeHotRecommendSearchReq req) {
        TicketRecommendReq ticketRecommendReq = new TicketRecommendReq();
        ticketRecommendReq.setChannelId(req.getChannelId());
        ticketRecommendReq.setCityId(ObjectUtils.isEmpty(req.getCityId()) ? Constant.AREA_HK : req.getCityId());
        Integer pageNum = ObjectUtils.isEmpty(req.getPage()) ? 1 : req.getPage();
        Integer pageSize = ObjectUtils.isEmpty(req.getSize()) ? ElasticSearchConstant.PAGE_SIZE : req.getSize();
        Result<PageResponse<ScenicTicketListDTO>> pageResponseResult = iScenicTicketEsSearchService.selectTicketRecommendList(ticketRecommendReq, pageNum, pageSize);
        List<HomeHotRecommendDTO> hotRecommendDTOS = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(pageResponseResult) && pageResponseResult.isSuccess()) {
            List<ScenicTicketListDTO> records = pageResponseResult.getData().getRecords();
            for (ScenicTicketListDTO record : records) {
                HomeHotRecommendDTO homeHotRecommendDTO = new HomeHotRecommendDTO();
                homeHotRecommendDTO.setId(record.getProductId());
                homeHotRecommendDTO.setBasePrice(record.getMoney());
                homeHotRecommendDTO.setCoverPhotoUrl(record.getPng());
                homeHotRecommendDTO.setTitle(record.getTitle());
                hotRecommendDTOS.add(homeHotRecommendDTO);
            }
        }
        return hotRecommendDTOS;
    }

    /**
     * 当地玩乐热门推荐检索
     *
     * @param req
     * @return
     */
    private List<HomeHotRecommendDTO> findLocalFunHotRecommenc(AppHomeHotRecommendSearchReq req) {
        PCLocalFunQueryReq pcLocalFunQueryReq = new PCLocalFunQueryReq();
        pcLocalFunQueryReq.setChannelId(req.getChannelId());
        pcLocalFunQueryReq.setCityId(req.getCityId());
        pcLocalFunQueryReq.setPageNo(ObjectUtils.isEmpty(req.getPage()) ? 1 : req.getPage());
        pcLocalFunQueryReq.setPageNum(ObjectUtils.isEmpty(req.getSize()) ? ElasticSearchConstant.PAGE_SIZE : req.getSize());
        Result<List<HotLocalFunDto>> data = iLocalFunAppProductService.getHotRecommends(pcLocalFunQueryReq);
        List<HotLocalFunDto> hotLocalFunDtos = data.getData();
        List<HomeHotRecommendDTO> hotRecommendDTOS = new ArrayList<>();
        for (HotLocalFunDto hotLocalFunDto : hotLocalFunDtos) {
            HomeHotRecommendDTO homeHotRecommendDTO = new HomeHotRecommendDTO();
            homeHotRecommendDTO.setId(hotLocalFunDto.getProductId());
            homeHotRecommendDTO.setCoverPhotoUrl(hotLocalFunDto.getCoverImage());
            homeHotRecommendDTO.setTitle(hotLocalFunDto.getTitle());
            // appHomeHotRecommendDTO.setIsHot(hotLocalFunDto.get); 暂无字段，待补
            homeHotRecommendDTO.setBasePrice(hotLocalFunDto.getPrice());
            hotRecommendDTOS.add(homeHotRecommendDTO);
        }
        return hotRecommendDTOS;
    }
}
